"""
Main GeneTrack runner

$Rev: 234 $ 
$Author: ialbert $ 
$Date: 2008-02-06 16:42:06 -0500 (Wed, 06 Feb 2008) $
"""

import sys

#
# add library to python path (as first entry)
#
sys.path =  [ 'library', 'library/library.zip' ] + sys.path

import atlas
from atlas import modcheck
from atlas import util, verify, commands
from optparse import OptionParser

def usage():
    "Returns the usage information"
    
    text = """
    
    python run.py <command> <conf_module>
    
    valid commands:
    
        test                 # runs the test suite
        execute conf_module  # executes the config module
        server  conf_module  # runs a server based on the config module

    The 'execute' and 'server' commands require a configuration 
    module. This module must be importable from the current python path.
    """
   
    return text

@util.stop_on_error
def execute():
    """
    Main genetrack runner
    """

    #
    # options will be parsed here
    #
    parser = OptionParser()
    parser.set_usage( usage() )
    parser.add_option( "-d", dest="debug", action='store_true', help='turns on debug messages' )
    (options, args) = parser.parse_args()

    #
    # setting debug level on will raise full tracebacks
    #
    if options.debug:
        atlas.disable_loglevel( 0 )
        util.debug_on()
        atlas.info( 'debug mode on' )
    else:
        atlas.disable_loglevel( 'DEBUG' ) 
        util.debug_off()

    #
    # insufficient arguments
    #
    if not args:
        parser.print_help()
        sys.exit()
    
    #
    # at least one command received
    #
    command = args[0]
    if command == 'test':
        from tests import test_all
        atlas.info( "self testing mode" )
        tick = util.Tick()
        test_all.execute()
        atlas.info( "finished in %s" % tick.tock()  )
        return

    # 
    # read off configuration module
    #
    if len(args) != 2:
        atlas.error( 'configuration module not specified' )
        sys.exit()

    modname = args[1]
    conf = atlas.module_import( modname )
    
    #
    # data analysis
    #
    if command == 'execute':
        tick = util.Tick()
        verify.check_dataconf( conf )
        atlas.info( "executing %s" % modname )  
        commands.execute( conf )
        atlas.info( "finished in %s" % tick.tock()  )
        return

    #
    # webserver
    #
    if command == 'server':
        verify.check_webconf( conf )
        atlas.info( "running the server on %s" % modname )   
        atlas.disable_loglevel() 
        atlas.save_pid( homedir='', fname='%s.pid' % modname )
        commands.server( conf )
        return
    #
    # nothing matched so, must be an error
    #
    atlas.error( "unknown command '%s' (execute python run.py for more info)" % command )

if __name__ == '__main__':
    try:
        #import psyco
        #psyco.full()
        pass
    except ImportError:
        # no accelerator, ignore
        pass

    execute()
